package nuonuo.com.aidl;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.List;

import Constant.Constant;
import service.AidlService;
import service.MyService;

public class MainActivity extends AppCompatActivity {

    private Button mBtnBind;
    private Button mBtnUnbind;
    private ServiceConnection mConnection;
    private Context mContext;
    private Messenger mService;
    private Messenger mReplyMessenger;
    private Button mAidlBindBtn;
    private Button mAidlUnbindBtn;
    private ServiceConnection mAidlConn;
    private String processName;
    private IBookManager mMananger;
    private Button mBtnAdd;
    private Button mBtnGetBooks;
    private Button mBtnGo;

    private IBinder.DeathRecipient mRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            if (mMananger != null){
                try {
                    mMananger.asBinder().linkToDeath(mRecipient,0);
                    mMananger = null;
                    bindService(intent,mAidlConn,Context.BIND_AUTO_CREATE);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int pid = android.os.Process.myPid();//获取进程pid
        processName = null;
        ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);//获取系统的ActivityManager服务
        for (ActivityManager.RunningAppProcessInfo appProcess : am.getRunningAppProcesses()){
            if(appProcess.pid == pid){
                processName = appProcess.processName;
                break;
            }
        }

        mConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                mService = new Messenger(iBinder);
                mReplyMessenger = new Messenger(new GetReplyHandler());
                Message mMsg = Message.obtain(null,Constant.MESSAGE_HANDLER_MSG);
                Bundle mData = new Bundle();
                mData.putString("data","hi,this is client");
                mMsg.setData(mData);
                mMsg.replyTo = mReplyMessenger;
                try {
                    mService.send(mMsg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        mAidlConn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                mMananger = IBookManager.Stub.asInterface(iBinder);
                try {
                    iBinder.linkToDeath(mRecipient,0);
                    mMananger.registOnBookChangedListener(mListener);
                    List<Book> list = mMananger.getBookList();
                    for (int i = 0; i < list.size(); i++) {
                        Log.i(Constant.TAG,list.get(i).getmBookName());
                    }
                    mMananger.addBook(new Book("03","android开发艺术探索"));
                    List<Book> list2 = mMananger.getBookList();
                    for (int i = 0; i < list2.size(); i++) {
                        Log.i(Constant.TAG,list2.get(i).getmBookName());
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        mContext = this;
        mBtnBind = (Button) findViewById(R.id.btn_bind);
        mBtnUnbind = (Button) findViewById(R.id.btn_unbind);
        mAidlBindBtn = (Button) findViewById(R.id.btn_bind_aidl);
        mAidlUnbindBtn = (Button) findViewById(R.id.btn_unbind_aidl);
        mBtnAdd = (Button) findViewById(R.id.btn_add_book);
        mBtnGetBooks = (Button) findViewById(R.id.btn_get_list);
        mBtnGo = (Button) findViewById(R.id.btn_go);
        setListener();
    }

    private IOnNewBookArrivedListener mListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onBookChanged(Book book) throws RemoteException {
            Log.i(Constant.TAG,"当前线程"+processName+"收到通知："+book.getmBookName());
        }
    };

    public static class GetReplyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.MESSAGE_REPLY_MSG:
                    Bundle mReply = msg.getData();
                    Log.i(Constant.TAG,mReply.getString("data"));
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    private void setListener() {
        mBtnBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(mContext, MyService.class);
                Constant.mTestNum = 2;
                Log.i(Constant.TAG,Constant.mTestNum+"");
                bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
            }
        });
        mBtnUnbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    unbindService(mConnection);
                }catch (IllegalArgumentException e){
                    Toast.makeText(mContext, "服务没有绑定", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mAidlBindBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent();
                intent.setClass(mContext, AidlService.class);
                bindService(intent,mAidlConn,Context.BIND_AUTO_CREATE);
            }
        });
        mAidlUnbindBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    unbindService(mAidlConn);
                }catch (IllegalArgumentException e){
                    Toast.makeText(mContext, "服务没有绑定", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mBtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    mMananger.addBook(new Book(index+"","name"+index));
                    index++;
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        mBtnGetBooks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    List<Book> bookList = mMananger.getBookList();
                    for (int i = 0; i < bookList.size(); i++) {
                        Log.i(Constant.TAG,bookList.get(i).getmBookName());
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        mBtnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,Main2Activity.class);
                startActivity(intent);
            }
        });
    }
    private int index = 20;
}
